<template>
  <!-- 因为通过二级路由实现,所以放在views下 -->
  <section class="singer-detail">
    <music-list
      :songs="songs"
      :title="title"
      :pic="pic"
      :loading="loading"
    ></music-list>
  </section>
</template>

<script type="text/ecmascript-6">
import { getSingerDetail } from '@/service/singer'
import { processSongs } from '@/service/song'
import MusicList from '@/components/music-list/music-list'
import storage from 'good-storage'
import { SINGER_KEY } from '@/assets/js/constant.js'

export default {
  name: 'singer-detail',
  props: {
    singer: Object
  },
  data() {
    return {
      songs: [],
      loading: true
    }
  },
  computed: {
    // 如果从props中传递数据那么获取传递的 否则从sessionStorage中取
    // 使用sessionStorage解决歌手歌单页面刷新缺少Mid报错的问题
    computedSinger() {
      let ret = null
      const singer = this.singer
      console.log(singer)
      // 如果从props传入了singer
      if (singer) {
        ret = singer
      } else {
        // 没从props中传入 那么从缓存中取
        const cachedSinger = storage.session.get(SINGER_KEY)
        // 如果值存在并且其中的mid属性与路由中的id是匹配的 那么证明是从当前页刷新的
        if (cachedSinger && cachedSinger.mid === this.$route.params.id) {
          ret = cachedSinger
        }
      }
      return ret
    },
    pic() {
      // 缓存数据 避免触发依赖收集 vue优化点
      const singer = this.computedSinger
      return singer && singer.pic
    },
    title() {
      const singer = this.computedSinger
      return singer && singer.name
    }
  },
  async created() {
    // 如果没有取到歌手数据 可能歌手Mid与路由中的id不匹配 那么computedSinger返回的就是Null 就执行一次保护 不执行后续逻辑
    if (!this.computedSinger) {
      // 当匹配失败时，返回上一级路由，matched[0]就是第一个匹配的路径
      const path = this.$route.matched[0].path
      // 当前id与缓存mid不匹配的时候，退回路由
      // 仅在刷新页面的时候生效 退回上一级路由
      this.$router.push({
        path
      })
      return
    }
    // 获取歌手的歌曲列表
    const result = await getSingerDetail(this.computedSinger)
    // console.log(result)
    // 获取歌单中所有歌曲的播放地址
    this.songs = await processSongs(result.songs)
    console.log(this.songs)
    // 当数据获取以后改为false 隐藏loading
    this.loading = false
  },
  components: {
    MusicList
  }
}
</script>

<style lang="scss" scoped>
  .singer-detail {
    position: fixed;
    z-index: 10;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: $color-background;
  }
</style>
